package com.dengdai.paylibrary.pay;

import android.content.Context;

import com.dengdai.applibrary.utils.Md5Utils;
import com.dengdai.paylibrary.entitys.WeChatEntity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * @说明 微信支付
 * @作者 LY
 * @时间 16/5/31 13:45
 * @邮箱 2743569843@qq.com
 * @版权 Copyright(c) 2016 LY-版权所有
 * @备注
 */
public class WeChatPayUtils {

    /**
     * 跳转到微信支付
     *
     * @param context
     * @param weChatEntity
     */
    public void startWeChatPay(Context context, WeChatEntity weChatEntity) {
        PayReq req = new PayReq();
        req.appId = weChatEntity.getAppId();
        req.partnerId = weChatEntity.getPartnerId();
        req.prepayId = weChatEntity.getPrepayId();
        req.packageValue = "prepay_id=" + weChatEntity.getPrepayId();
        req.nonceStr = weChatEntity.getNonceStr();
        req.timeStamp = weChatEntity.getTimeStamp();
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
        req.sign = genAppSign(signParams, weChatEntity.getAppKey());
        IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);
        msgApi.registerApp(weChatEntity.getAppId());
        msgApi.sendReq(req);
    }

    private String genNonceStr() {
        Random random = new Random();
        return Md5Utils.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private String genAppSign(List<NameValuePair> params, String apiKey) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(apiKey);
        String appSign = Md5Utils.getMessageDigest(sb.toString().getBytes());
        return appSign;
    }
}
